package de.tabreaderandroid.tabreader.model;

import java.util.LinkedList;
import java.util.List;

import de.tabreaderandroid.tabreader.utils.InvalidTabFormatException;

/**
 * A class encapsulating a number of {@link Bar}s. It is used to group those
 * bars in the same way that they where in the origin document. This is needed
 * to keep a unique origin line even if line breaks are added between bars of a
 * group.
 * 
 * @author André Stannek
 * 
 */
public class BarGroup extends TabFileElement {

	private TabString[] strings;

	/**
	 * Creates an new {@link BarGroup} with an origin index.
	 * 
	 * @param originIndex
	 *            the index of the first line of this group in the origin
	 *            document
	 * @see TabFileElement#TabFileElement(int)
	 */
	public BarGroup(int originIndex) {
		super(originIndex);
		strings = new TabString[6];
	}

	@Override
	public List<String> getLines(int maxCharWidth)
			throws InvalidTabFormatException {
		for (TabString string : strings) {
			if (string.getMaxBarLength() + 2 > maxCharWidth) {
				throw new InvalidTabFormatException(
						"Line length to short to display bar group!");
			}
		}
		List<String> result = new LinkedList<String>();
		int appendedBars = 0;
		int maxBars = strings[0].getBars().length;
		while (appendedBars < maxBars) {
			appendedBars += appendBars(maxCharWidth, result, appendedBars);
		}
		return result;
	}

	private int appendBars(int maxCharWidth, List<String> result, int startBar) {

		int appendedBars = 0;
		for (TabString string : strings) {
			appendedBars = appendBarsForString(string, maxCharWidth, result,
					startBar);
		}
		result.add("");
		return appendedBars;
	}

	private int appendBarsForString(TabString string, int maxCharWidth,
			List<String> result, int startBar) {

		StringBuilder builder = new StringBuilder("|");
		int bar = startBar;
		int appendedBars = 0;
		String[] bars = string.getBars();
		while (bar < bars.length
				&& builder.length() + bars[bar].length() + 1 < maxCharWidth) {
			builder.append(bars[bar]).append("|");
			bar++;
			appendedBars++;
		}
		result.add(builder.toString());
		return appendedBars;
	}

	public void setString(int i, TabString tabString) {
		strings[i] = tabString;
	}
}
